package com.innovation.ic.sc.base.service.sc.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.base.Strings;
import com.innovation.ic.b1b.framework.util.DateUtils;
import com.innovation.ic.b1b.framework.util.StringUtils;
import com.innovation.ic.sc.base.mapper.sc.AdvantageModelMapper;
import com.innovation.ic.sc.base.model.erp9_pvecrm.SpecialsSCTopView;
import com.innovation.ic.sc.base.model.sc.ActionMessage;
import com.innovation.ic.sc.base.model.sc.AdvantageBrand;
import com.innovation.ic.sc.base.model.sc.AdvantageModel;
import com.innovation.ic.sc.base.model.sc.Inventory;
import com.innovation.ic.sc.base.pojo.constant.model.AdvantageConstants;
import com.innovation.ic.sc.base.pojo.constant.model.AdvantageModelConstants;
import com.innovation.ic.sc.base.pojo.constant.Constants;
import com.innovation.ic.sc.base.pojo.constant.handler.RabbitMqConstants;
import com.innovation.ic.sc.base.pojo.enums.*;
import com.innovation.ic.sc.base.pojo.variable.*;
import com.innovation.ic.sc.base.pojo.variable.advantageModel.*;
import com.innovation.ic.sc.base.pojo.variable.inventory.MayApplyInventoryModelPojo;
import com.innovation.ic.sc.base.service.ServiceHelper;
import com.innovation.ic.sc.base.service.sc.ActionMessageService;
import com.innovation.ic.sc.base.service.sc.AdvantageModelService;
import com.innovation.ic.sc.base.vo.advantageModel.AdvantageModelDeleteVo;
import com.innovation.ic.sc.base.vo.advantageModel.*;
import io.swagger.models.auth.In;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @desc   AdvantageModelService的具体实现类
 * @author linuo
 * @time   2022年8月29日13:52:55
 */
@Service
@Transactional
public class AdvantageModelServiceImpl extends ServiceImpl<AdvantageModelMapper, AdvantageModel> implements AdvantageModelService {
    private static final Logger log = LoggerFactory.getLogger(AdvantageModelServiceImpl.class);

    @Resource
    private ServiceHelper serviceHelper;

    @Resource
    private ActionMessageService actionMessageService;

    /**
     * 将advantage_model表中所有型号的所属品牌数据导入到redis，提供给根据型号查询所属品牌接口使用
     */
    @Override
    public void initAdvantageModelBrand() {
        // 删除redis中的优势型号数据
        Boolean deleteResult = serviceHelper.getRedisManager().delRedisDataByKeyPrefix(RedisKeyPrefixEnum.ADVANTAGE_MODEL_BRAND_DATA.getCode() + "*");
        if(deleteResult){
            log.info("删除[{}]开头的数据成功", RedisKeyPrefixEnum.ADVANTAGE_MODEL_BRAND_DATA.getCode());
        }

        // 查询优势型号表中的所有供应商id
        List<String> enterpriseIds = serviceHelper.getAdvantageModelMapper().selectEnterpriseIdList();
        if(enterpriseIds != null && enterpriseIds.size() > 0){
            for(String enterpriseId : enterpriseIds){
                // 查询当前供应商下的所有型号数据
                List<String> partNumbers = serviceHelper.getAdvantageModelMapper().selectPartNumberListByEnterpriseId(enterpriseId);
                if(partNumbers != null && partNumbers.size() > 0){
                    for(String partNumber : partNumbers){
                        // 查询当前型号的所属品牌
                        List<String> result = serviceHelper.getInventoryMapper().queryBrandsByPartNumber(partNumber, enterpriseId);
                        if(result != null && result.size() > 0){
                            String key = RedisKeyPrefixEnum.ADVANTAGE_MODEL_BRAND_DATA.getCode() + "_" + partNumber + "_" + enterpriseId;
                            log.info(key);
                            String apiResultJson = JSONObject.toJSONString(result, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue);
                            serviceHelper.getRedisManager().set(key, apiResultJson);
                        }
                    }
                }
            }
        }
    }

    /**
     * 初始化优势型号数据
     */
    @Override
    public void initAdvantageModelData() {
        // 删除redis中的优势型号数据
        Boolean deleteResult = serviceHelper.getRedisManager().delRedisDataByKeyPrefix(RedisKeyPrefixEnum.ADVANTAGE_MODEL_DATA.getCode() + "*");
        if(deleteResult){
            log.info("删除[{}]开头的数据成功", RedisKeyPrefixEnum.ADVANTAGE_MODEL_DATA.getCode());
        }

        // 获取优势型号表的所有数据
        List<AdvantageModel> advantageModels = serviceHelper.getAdvantageModelMapper().selectList(null);
        if(advantageModels != null && advantageModels.size() > 0){
            for(AdvantageModel advantageModel : advantageModels){
                if(!Strings.isNullOrEmpty(advantageModel.getPartNumber()) && !Strings.isNullOrEmpty(advantageModel.getBrand()) && !Strings.isNullOrEmpty(advantageModel.getEnterpriseId())){
                    String key = RedisKeyPrefixEnum.ADVANTAGE_MODEL_DATA.getCode() + "_" + advantageModel.getPartNumber() + "_" + advantageModel.getBrand() + "_" + advantageModel.getEnterpriseId();
                    String apiResultJson = JSONObject.toJSONString(advantageModel, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue);
                    serviceHelper.getRedisManager().set(key, apiResultJson);
                }
            }
        }
        log.info("导入[{}]开头的数据成功", RedisKeyPrefixEnum.ADVANTAGE_MODEL_DATA.getCode());
    }

    /**
     * 处理优势型号通知的mq消息
     * @param brand 品牌
     * @param partNumber 型号
     * @param enterpriseId 供应商id
     * @param id erpid
     * @return 返回处理结果
     */
    @Override
    public ServiceResult<Boolean> handleAdvantageModelNotifyMqMsg(String brand, String partNumber, String enterpriseId, String id) {
        Boolean result = Boolean.FALSE;

        // 根据条件查询优势型号数据
        Map<String, String> map = new HashMap<>();
        map.put(AdvantageModelConstants.PART_NUMBER, partNumber);
        map.put(AdvantageModelConstants.BRAND_FIELD, brand);
        map.put(Constants.ENTERPRISE_ID, enterpriseId);

        // 根据查询条件获取数据id
        List<Integer> idList = serviceHelper.getInventoryMapper().selectIdListByParam(map);
        log.info("根据查询条件获取数据id结果获取到[{}]条", idList.size());
        if(idList != null && !idList.isEmpty()){
            UpdateWrapper<Inventory> updateWrapper = new UpdateWrapper<>();
            updateWrapper.in(Constants.ID, idList);

            Inventory inventory = new Inventory();
            inventory.setErpId(id);

            int update = serviceHelper.getInventoryMapper().update(inventory, updateWrapper);
            if(update > 0){
                log.info("库存数据补全erpId成功,id:[{}]", idList.toString());
                result = Boolean.TRUE;
            }
        }

        ServiceResult<Boolean> serviceResult = new ServiceResult<>();
        serviceResult.setSuccess(result);
        serviceResult.setResult(result);
        serviceResult.setMessage(ServiceResult.OPERATE_SUCCESS);
        return serviceResult;
    }

    /**
     * 判断优势型号数据中是否已保存erp的id
     * @param idList id集合
     * @return 返回判断结果
     */
    @Override
    public ServiceResult<Boolean> judgeIfSaveErpId(List<Integer> idList) {
        boolean result = Boolean.TRUE;
        String message = null;

        for(Integer id : idList){
            AdvantageModel advantageModel = serviceHelper.getAdvantageModelMapper().selectById(id);
            if(advantageModel != null && Strings.isNullOrEmpty(advantageModel.getErpId())){
                result = Boolean.FALSE;
                message = "数据正在处理，请稍后操作";
                break;
            }
        }

        ServiceResult<Boolean> serviceResult = new ServiceResult<>();
        serviceResult.setResult(result);
        serviceResult.setSuccess(result);
        serviceResult.setMessage(message);
        return serviceResult;
    }

    /**
     * 更新优势型号生效状态
     * @param map 参数
     * @return 返回更新结果
     */
    @Override
    public ServiceResult<Boolean> updateStatusByParam(Map<String, Object> map) throws IOException {
        Boolean result = Boolean.FALSE;
        String message = ServiceResult.UPDATE_FAIL;

        int i = serviceHelper.getAdvantageModelMapper().updateStatusByParam(map);
        if(i > 0){
            result = Boolean.TRUE;
            message = ServiceResult.UPDATE_SUCCESS;

            String brand = (String) map.get(AdvantageModelConstants.BRAND_FIELD);
            String partNumber = (String) map.get(AdvantageModelConstants.PART_NUMBER);
            Integer status = (Integer) map.get(AdvantageModelConstants.ADVANTAGE_STATUS);
            String enterpriseId = (String) map.get(Constants.ENTERPRISE_ID);

            if(status.intValue() == InventoryOperateTypeEnum.DOWN_SHELVES.getCode().intValue()){
                // 库存下架 -> 需要取消优势型号推送mq消息
                //cancleAdvantageModelSendMqMsg(brand, partNumber, enterpriseId);
            }

            if(status.intValue() == InventoryOperateTypeEnum.UP_SHELVES.getCode().intValue()){
                // 库存上架 -> 需要将优势型号状态修改为生效并推送mq消息
                restoreAdvantageModelSendMqMsg(brand, partNumber, enterpriseId);
            }
        }

        ServiceResult<Boolean> serviceResult = new ServiceResult<>();
        serviceResult.setResult(result);
        serviceResult.setSuccess(result);
        serviceResult.setMessage(message);
        return serviceResult;
    }

    /**
     * 根据型号数组批量判断是否为优势型号
     * @param advantageModelBatchJudgeModelStatusVo 批量判断是否为优势型号的Vo类
     * @return 返回判断结果
     */
    @Override
    public ServiceResult<AdvantageModelBatchJudgeModelStatusRespPojo> batchJudgeIfAdvantageModelByModelArray(AdvantageModelBatchJudgeModelStatusVo advantageModelBatchJudgeModelStatusVo) {
        AdvantageModelBatchJudgeModelStatusRespPojo advantageModelBatchJudgeStatusRespPojo = new AdvantageModelBatchJudgeModelStatusRespPojo();
        List<AdvantageModelJudgeModelStatusRespPojo> resultList = new ArrayList<>();

        List<String> partNumberList = advantageModelBatchJudgeModelStatusVo.getPartNumberList();
        for(String partNumber : partNumberList){
            // 判断是否为优势型号
            List<AdvantageModelJudgeModelStatusRespPojo> result = judgeIfAdvantageModelByPartNumber(partNumber);
            resultList.addAll(result);
        }

        advantageModelBatchJudgeStatusRespPojo.setResultList(resultList);

        ServiceResult<AdvantageModelBatchJudgeModelStatusRespPojo> serviceResult = new ServiceResult<>();
        serviceResult.setSuccess(Boolean.TRUE);
        serviceResult.setResult(advantageModelBatchJudgeStatusRespPojo);
        serviceResult.setMessage(ServiceResult.SELECT_SUCCESS);
        return serviceResult;
    }

    /**
     * 根据型号查询所属品牌
     * @param partNumber 型号
     * @return 返回查询结果
     */
    @Override
    public ServiceResult<List<String>> queryBrandsByPartNumber(String partNumber, AuthenticationUser authenticationUser) {
        List<String> result;

        // 根据型号、供应商id查询型号的所属品牌
        String key = RedisKeyPrefixEnum.ADVANTAGE_MODEL_BRAND_DATA.getCode() + "_" + partNumber + "_" + authenticationUser.getEpId();
        String data = (String) serviceHelper.getRedisManager().get(key);
        if(!Strings.isNullOrEmpty(data)){
            result = JSONArray.parseArray(data, String.class);
        }else{
            result = serviceHelper.getInventoryMapper().queryBrandsByPartNumber(partNumber, authenticationUser.getEpId());
            if(result != null && result.size() > 0){
                String apiResultJson = JSONObject.toJSONString(result, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue);
                serviceHelper.getRedisManager().set(key, apiResultJson);
            }
        }

        ServiceResult<List<String>> serviceResult = new ServiceResult<>();
        serviceResult.setSuccess(Boolean.TRUE);
        serviceResult.setMessage(ServiceResult.SELECT_SUCCESS);
        serviceResult.setResult(result);
        return serviceResult;
    }

    /**
     * 根据品牌、型号数组批量判断是否为优势型号
     * @param advantageModelBatchJudgeStatusVo 批量判断是否为优势型号的Vo类
     * @return 返回判断结果
     */
    @Override
    public ServiceResult<AdvantageModelBatchJudgeStatusRespPojo> batchJudgeIfAdvantageModelByBrandModelArray(AdvantageModelBatchJudgeStatusVo advantageModelBatchJudgeStatusVo) {
        AdvantageModelBatchJudgeStatusRespPojo advantageModelBatchJudgeStatusRespPojo = new AdvantageModelBatchJudgeStatusRespPojo();
        List<AdvantageModelJudgeStatusRespPojo> resultList = new ArrayList<>();

        List<AdvantageModelJudgeStatusVo> advantageModelList = advantageModelBatchJudgeStatusVo.getAdvantageModelList();
        for(AdvantageModelJudgeStatusVo advantageModelJudgeStatusVo : advantageModelList){
            if (!StringUtils.validateParameter(advantageModelJudgeStatusVo.getPartNumber())
                    || !StringUtils.validateParameter(advantageModelJudgeStatusVo.getBrand())) {
                ServiceResult<AdvantageModelBatchJudgeStatusRespPojo> serviceResult = new ServiceResult<>();
                serviceResult.setSuccess(Boolean.FALSE);
                serviceResult.setMessage("调用接口【/api/v1/advantageModel/batchJudgeIfAdvantageModel时，参数advantageModelList中的partNumber和brand不能为空");
                serviceResult.setResult(null);
                return serviceResult;
            }

            // 判断是否为优势型号
            List<AdvantageModelJudgeStatusRespPojo> result = judgeIfAdvantageModel(advantageModelJudgeStatusVo.getBrand(), advantageModelJudgeStatusVo.getPartNumber(),
                    advantageModelJudgeStatusVo.getNeedGoodsCount());
            resultList.addAll(result);
        }
        advantageModelBatchJudgeStatusRespPojo.setResultList(resultList);

        ServiceResult<AdvantageModelBatchJudgeStatusRespPojo> serviceResult = new ServiceResult<>();
        serviceResult.setSuccess(Boolean.TRUE);
        serviceResult.setResult(advantageModelBatchJudgeStatusRespPojo);
        serviceResult.setMessage(ServiceResult.SELECT_SUCCESS);
        return serviceResult;
    }

    /**
     * 判断是否为优势型号
     * @param advantageModelJudgeStatusVo 判断是否为优势型号的Vo类
     * @return 返回判断结果
     */
    @Override
    public ServiceResult<List<AdvantageModelJudgeStatusRespPojo>> judgeIfAdvantageModel(AdvantageModelJudgeStatusVo advantageModelJudgeStatusVo) {
        List<AdvantageModelJudgeStatusRespPojo> result = judgeIfAdvantageModel(advantageModelJudgeStatusVo.getBrand(), advantageModelJudgeStatusVo.getPartNumber(),
                advantageModelJudgeStatusVo.getNeedGoodsCount());

        ServiceResult<List<AdvantageModelJudgeStatusRespPojo>> serviceResult = new ServiceResult<>();
        serviceResult.setSuccess(Boolean.TRUE);
        serviceResult.setMessage(ServiceResult.SELECT_SUCCESS);
        serviceResult.setResult(result);
        return serviceResult;
    }

    /**
     * 校验当前型号是否已添加
     * @param advantageModelCheckVo 优势型号校验的Vo类
     * @param authenticationUser 用户信息
     * @return 返回校验结果
     */
    @Override
    public ServiceResult<Boolean> checkAdvantageModelIfAdd(AdvantageModelCheckVo advantageModelCheckVo, AuthenticationUser authenticationUser) {
        ServiceResult<Boolean> serviceResult = new ServiceResult<>();

        Boolean result = Boolean.FALSE;
        // 根据品牌、型号查询优势型号数据
        String key = RedisKeyPrefixEnum.ADVANTAGE_MODEL_DATA.getCode() + "_" + advantageModelCheckVo.getPartNumber() + "_" + advantageModelCheckVo.getBrand() + "_" + authenticationUser.getEpId();
        String data = (String) serviceHelper.getRedisManager().get(key);
        if(!Strings.isNullOrEmpty(data)){
            JSONObject json = (JSONObject) JSONObject.parse(data);
            if(json != null && !json.isEmpty()){
                result = Boolean.TRUE;
            }
        }else{
            // 查询数据库
            QueryWrapper<AdvantageModel> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq(AdvantageModelConstants.PART_NUMBER_FIELD, advantageModelCheckVo.getPartNumber());
            queryWrapper.eq(AdvantageModelConstants.BRAND_FIELD, advantageModelCheckVo.getBrand());
            queryWrapper.eq(Constants.ENTERPRISE_ID_FIELD, authenticationUser.getEpId());
            List<AdvantageModel> advantageModels = serviceHelper.getAdvantageModelMapper().selectList(queryWrapper);
            if(advantageModels != null && advantageModels.size() > 0){
                result = Boolean.TRUE;

                AdvantageModel advantageModel = advantageModels.get(0);

                // 添加优势型号信息到redis
                addAdvantangeModelToRedis(advantageModel);
            }
        }

        serviceResult.setMessage(ServiceResult.SELECT_SUCCESS);
        serviceResult.setSuccess(Boolean.TRUE);
        serviceResult.setResult(result);
        return serviceResult;
    }

    /**
     * 优势型号再次发起审核
     * @param advantageModelAgainInitiateVo 优势型号再次发起审核接口的Vo类
     * @param authenticationUser 用户信息
     * @return 返回发起审核结果
     */
    @Override
    public ServiceResult<Boolean> againInitiate(AdvantageModelAgainInitiateVo advantageModelAgainInitiateVo, AuthenticationUser authenticationUser) throws IOException, ParseException {
        ServiceResult<Boolean> serviceResult = new ServiceResult<>();
        boolean result = Boolean.FALSE;
        String message = null;

        int count = 0;

        // 全部发起审核
        if(advantageModelAgainInitiateVo.getIsAll() != null && advantageModelAgainInitiateVo.getIsAll()){
            Map<String, String> map = new HashMap<>();
            map.put(AdvantageModelConstants.PART_NUMBER, advantageModelAgainInitiateVo.getPartNumber());
            map.put(AdvantageModelConstants.BRAND_FIELD, advantageModelAgainInitiateVo.getBrand());
            map.put(AdvantageModelConstants.CREATE_USER, advantageModelAgainInitiateVo.getCreateUser());
            map.put(AdvantageModelConstants.AUDIT_STATUS, advantageModelAgainInitiateVo.getAuditStatus());
            map.put(AdvantageModelConstants.ADVANTAGE_STATUS, advantageModelAgainInitiateVo.getAdvantageStatus());
            map.put(Constants.ENTERPRISE_ID, authenticationUser.getEpId());

            // 根据查询条件获取需要发起审核的数据id
            List<Integer> idList = serviceHelper.getAdvantageModelMapper().selectAgainInitiateIdList(map);
            if(idList != null && idList.size() > 0){
                for(Integer id : idList){
                    // 更新优势型号信息 推送mq消息
                    int i = updateAdvantageModelInitiateStatusSendMqMsg(id, advantageModelAgainInitiateVo);
                    if(i > 0){
                        count++;
                        result = Boolean.TRUE;
                        message = ServiceResult.UPDATE_SUCCESS;
                    }
                }
            }
        }else{
            for(Integer id : advantageModelAgainInitiateVo.getIdList()){
                // 校验当前优势型号数据是否为审核拒绝或审核通过且状态为无效的数据
                Boolean checkResult = checkAdvantageModelStatusIfInvalid(id);
                if(!checkResult){
                    log.info("当前优势型号数据不是审核拒绝数据或审核通过且状态无效的数据,无法再次发起审核,优势型号数据id:[{}]", id);
                    continue;
                }

                // 更新优势型号信息 推送mq消息
                int i = updateAdvantageModelInitiateStatusSendMqMsg(id, advantageModelAgainInitiateVo);
                if(i > 0){
                    count++;
                    result = Boolean.TRUE;
                    message = ServiceResult.UPDATE_SUCCESS;
                }
            }
        }

/*        for(Integer id : advantageModelAgainInitiateVo.getIdList()){
            // 校验当前优势型号数据是否为审核拒绝或审核通过且状态为无效的数据
            Boolean checkResult = checkAdvantageModelStatusIfInvalid(id);
            if(!checkResult){
                log.info("当前优势型号数据不是审核拒绝数据或审核通过且状态无效的数据,无法再次发起审核,优势型号数据id:[{}]", id);
                continue;
            }

            // 更新优势型号信息 推送mq消息
            int i = updateAdvantageModelInitiateStatusSendMqMsg(id, advantageModelAgainInitiateVo);
            if(i > 0){
                count++;
                result = Boolean.TRUE;
                message = ServiceResult.UPDATE_SUCCESS;
            }
        }*/

        // 所有数据均无法提交审核时返回信息给前端响应
        if(count == 0){
            message = "再次发起审核的数据需要满足审核状态为审核拒绝或审核通过且优势状态无效,请您确认状态后重新发起操作";
        }

        serviceResult.setSuccess(result);
        serviceResult.setResult(result);
        serviceResult.setMessage(message);
        return serviceResult;
    }

    /**
     * 更新优势型号审核状态 推送mq消息
     * @param id 优势型号id
     * @param advantageModelAgainInitiateVo 优势型号再次发起审核接口的Vo类
     * @return 返回更新结果
     */
    private int updateAdvantageModelInitiateStatusSendMqMsg(Integer id, AdvantageModelAgainInitiateVo advantageModelAgainInitiateVo) throws IOException, ParseException {
        int result = 0;

        // 修改优势型号数据审核状态为待审核并发送mq消息到erp
        UpdateWrapper<AdvantageModel> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq(Constants.ID, id);

        AdvantageModel advantageModel = new AdvantageModel();
        advantageModel.setAuditStatus(AuditStatusEnum.PENDING.getScStatusCode());

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        advantageModel.setValidityDateStart(sdf.parse(advantageModelAgainInitiateVo.getValidityDateStart()));
        advantageModel.setValidityDateEnd(sdf.parse(advantageModelAgainInitiateVo.getValidityDateEnd()));
        if(!Strings.isNullOrEmpty(advantageModelAgainInitiateVo.getRemark())){
            advantageModel.setRemark(advantageModelAgainInitiateVo.getRemark());
        }
        int update = serviceHelper.getAdvantageModelMapper().update(advantageModel, updateWrapper);
        if(update > 0){
            result = 1;
            log.info("修改优势型号数据状态成功,id:[{}]", id);

            // 从redis中删除优势型号信息
            advantageModel = serviceHelper.getAdvantageModelMapper().selectById(id);
            deleteAdvantageModelFromRedis(advantageModel);

            // 发送mq消息到erp
            sendMqMsgToErpUpdateAdvantageModel(serviceHelper.getAdvantageModelMapper().selectById(id));
        }

        return result;
    }

    /**
     * 推送mq消息到erp再次发起审批
     * @param advantageModel 优势型号信息
     */
    private void sendMqMsgToErpUpdateAdvantageModel(AdvantageModel advantageModel) throws IOException {
        if(advantageModel != null){
            SpecialsScTopViewUpdatePojo specialsScTopViewUpdatePojo = new SpecialsScTopViewUpdatePojo();
            specialsScTopViewUpdatePojo.setID(advantageModel.getErpId());
            specialsScTopViewUpdatePojo.setEnterpriseID(advantageModel.getEnterpriseId());
            specialsScTopViewUpdatePojo.setType(advantageModel.getType());
            specialsScTopViewUpdatePojo.setPartNumber(advantageModel.getPartNumber());
            specialsScTopViewUpdatePojo.setBrand(advantageModel.getBrand());
            specialsScTopViewUpdatePojo.setStartDate(advantageModel.getValidityDateStart());
            specialsScTopViewUpdatePojo.setEndDate(advantageModel.getValidityDateEnd());
            specialsScTopViewUpdatePojo.setCreator(advantageModel.getCreateUser());
            specialsScTopViewUpdatePojo.setSummary(advantageModel.getRemark());
            JSONObject json = (JSONObject) JSONObject.toJSON(specialsScTopViewUpdatePojo);

            // 包装发送到rabbitmq的消息内容
            JSONObject result = serviceHelper.packageSendRabbitMqMsgData(json, RabbitMqConstants.SC_ERP_UPDATE_SPECIAL_QUEUE);

            log.info("推送给rabbitmq的交换机:[{}],队列:[{}]的消息内容为:[{}]", RabbitMqConstants.SC_ERP_EXCHANGE, RabbitMqConstants.SC_ERP_UPDATE_SPECIAL_QUEUE, result.toString());
            serviceHelper.getRabbitMqManager().basicPublish(RabbitMqConstants.SC_ERP_EXCHANGE, RabbitMqConstants.SC_TO_ERP_CRM_QUEUE_NAME, RabbitMqConstants.SC_ERP_UPDATE_SPECIAL_QUEUE, null, result.toString().getBytes());
        }
    }

    /**
     * 删除erp导入的数据
     * @return 返回删除结果
     */
    @Override
    public ServiceResult<Boolean> deleteErpImportData() {
        ServiceResult<Boolean> serviceResult = new ServiceResult<>();

        QueryWrapper<AdvantageModel> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(AdvantageModelConstants.SOURCE_FIELD, AdvantageModelSourceEnum.ERP_IMPORT.getCode());
        serviceHelper.getAdvantageModelMapper().delete(queryWrapper);

        serviceResult.setMessage(ServiceResult.DELETE_SUCCESS);
        serviceResult.setSuccess(Boolean.TRUE);
        serviceResult.setResult(Boolean.TRUE);
        return serviceResult;
    }

    /**
     * 校验当前型号是否为已有型号
     * @param advantageModelCheckVo 优势型号校验的Vo类
     * @param authenticationUser 用户信息
     * @return 返回校验结果
     */
    @Override
    public ServiceResult<Boolean> checkAdvantageModelIfHave(AdvantageModelCheckVo advantageModelCheckVo, AuthenticationUser authenticationUser) {
        ServiceResult<Boolean> serviceResult = new ServiceResult<>();

        Boolean result = Boolean.FALSE;

        // 查询库存表中包含当前品牌、型号数据数量
        Long count = serviceHelper.getInventoryMapper().selectInventoryCount(advantageModelCheckVo, authenticationUser.getEpId());
        if(count > 0){
            result = Boolean.TRUE;
        }

        serviceResult.setMessage(ServiceResult.DELETE_SUCCESS);
        serviceResult.setSuccess(Boolean.TRUE);
        serviceResult.setResult(result);
        return serviceResult;
    }

    /**
     * 优势型号删除mq信息处理
     * @param specialsScTopViewCloseDelPojo 优势型号删除信息
     * @return 返回处理结果
     */
    @Override
    public ServiceResult<Boolean> handleAdvantageModelDeleteMqMsg(SpecialsScTopViewCloseDelPojo specialsScTopViewCloseDelPojo) {
        ServiceResult<Boolean> serviceResult = new ServiceResult<>();

        // 根据供应商id、品牌、型号查询sc的优势型号信息
        List<Inventory> inventorys = selectAdvantageModelDataByEpIdPartNoBrand(specialsScTopViewCloseDelPojo.getEnterpriseID(), specialsScTopViewCloseDelPojo.getPartNumber(), specialsScTopViewCloseDelPojo.getBrand());
        if(inventorys != null && inventorys.size() > 0){
            for(Inventory inventory : inventorys){
                // 更新优势型号的优势状态
                serviceHelper.getInventoryMapper().deleteById(inventory.getId());
            }
        }

        serviceResult.setMessage(ServiceResult.DELETE_SUCCESS);
        serviceResult.setSuccess(Boolean.TRUE);
        serviceResult.setResult(Boolean.TRUE);
        return serviceResult;
    }

    /**
     * 优势型号取消信息处理
     * @param specialsScTopViewCloseDelPojo 优势型号取消信息
     * @return 返回处理结果
     */
    @Override
    public ServiceResult<Boolean> handleAdvantageModelCloseMqMsg(SpecialsScTopViewCloseDelPojo specialsScTopViewCloseDelPojo) {
        ServiceResult<Boolean> serviceResult = new ServiceResult<>();

        // 根据供应商id、品牌、型号查询sc的优势型号信息
        QueryWrapper<Inventory> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(Constants.ERP_ID_FIELD, specialsScTopViewCloseDelPojo.getID());
        List<Inventory> inventorys = serviceHelper.getInventoryMapper().selectList(queryWrapper);
        if(inventorys != null){
            for(Inventory inventory : inventorys){
                // 更新库存表优势型号的优势状态
                int update = serviceHelper.getInventoryMapper().updateAdvantageStatus(inventory.getId(), AdvantageStatusEnum.INVALID.getScStatusCode());
                if(update > 0){
                    log.info("取消优势型号状态成功,库存id:[{}]", inventory.getId());
                }else{
                    log.info("取消优势型号状态失败,库存id:[{}]", inventory.getId());
                }
            }
        }

        serviceResult.setMessage(ServiceResult.UPDATE_SUCCESS);
        serviceResult.setSuccess(Boolean.TRUE);
        serviceResult.setResult(Boolean.TRUE);
        return serviceResult;
    }

    /**
     * 优势型号审批信息处理
     * @param erpId erpId
     * @param status 状态(200通过 300否决)
     * @param summary 备注
     * @return 返回处理结果
     */
    @Override
    public ServiceResult<Boolean> handleAdvantageModelAuditMqMsg(String erpId, String status, String summary) {
        ServiceResult<Boolean> serviceResult = new ServiceResult<>();

        // 根据erpId查询sc的优势型号信息
        QueryWrapper<Inventory> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(AdvantageConstants.ERP_ID_FIELD, erpId);
        List<Inventory> inventorys = serviceHelper.getInventoryMapper().selectList(queryWrapper);
        if(inventorys != null && inventorys.size() > 0){
            for(Inventory inventory : inventorys){
                // 更新优势型号信息
                SpecialsSCTopView specialsScTopView = new SpecialsSCTopView();
                specialsScTopView.setAuditStatus(Integer.valueOf(status));
                specialsScTopView.setSummary(summary);
                updateAdvantageModel(Boolean.TRUE, inventory, specialsScTopView);
            }
        }

        serviceResult.setMessage(ServiceResult.UPDATE_SUCCESS);
        serviceResult.setSuccess(Boolean.TRUE);
        serviceResult.setResult(Boolean.TRUE);
        return serviceResult;
    }

    /**
     * 处理优势型号的rabbitmq消息
     * @param specialsScTopView 优势型号内容
     * @return 返回处理结果
     */
    @Override
    public ServiceResult<Boolean> handleAdvantageModelAddMqMsg(SpecialsSCTopView specialsScTopView) {
        ServiceResult<Boolean> serviceResult = new ServiceResult<>();

        // 根据供应商id、品牌、型号查询sc的优势型号信息
        List<Inventory> inventorys = selectAdvantageModelDataByEpIdPartNoBrand(specialsScTopView.getEnterpriseID(), specialsScTopView.getPartNumber(), specialsScTopView.getBrand());
        if(inventorys != null && inventorys.size() > 0){
            for(Inventory inventory : inventorys){
                // 更新优势型号信息
                updateAdvantageModel(Boolean.FALSE, inventory, specialsScTopView);
            }
        }else{
            log.info("未获取到品牌:[[{}]、型号:[{}]的库存信息,无法更新优势型号状态,忽略此数据", specialsScTopView.getBrand(), specialsScTopView.getPartNumber());
        }

        serviceResult.setMessage(ServiceResult.INSERT_SUCCESS);
        serviceResult.setSuccess(Boolean.TRUE);
        serviceResult.setResult(Boolean.TRUE);
        return serviceResult;
    }

    /**
     * 申请延期
     * @param advantageModelApplyDelayVo 优势型号申请延期的Vo类
     * @return 返回操作结果
     */
    @Override
    public ServiceResult<Boolean> applyDelay(AdvantageModelApplyDelayVo advantageModelApplyDelayVo) throws IOException {
        ServiceResult<Boolean> serviceResult = new ServiceResult<>();

        // 发送mq消息，申请延期
        AdvantageModel advantageModel = serviceHelper.getAdvantageModelMapper().selectById(advantageModelApplyDelayVo.getId());
        if(advantageModel != null && advantageModel.getId() != null){
            SpecialsScTopViewAddPojo specialsScTopViewAddPojo = new SpecialsScTopViewAddPojo();
            specialsScTopViewAddPojo.setPartNumber(advantageModel.getPartNumber());
            specialsScTopViewAddPojo.setBrand(advantageModel.getBrand());
            specialsScTopViewAddPojo.setEnterpriseID(advantageModel.getEnterpriseId());
            specialsScTopViewAddPojo.setEndDate(DateUtils.stringToDate(advantageModelApplyDelayVo.getDelayDate(), Constants.DATE_PATTERN));
            JSONObject json = (JSONObject) JSONObject.toJSON(specialsScTopViewAddPojo);

            // 包装发送到rabbitmq的消息内容
            JSONObject result = serviceHelper.packageSendRabbitMqMsgData(json, RabbitMqConstants.SC_ERP_ADD_QUEUE);

            log.info("推送给rabbitmq的交换机:[{}],队列:[{}]的消息内容为:[{}]", RabbitMqConstants.SC_ERP_EXCHANGE, RabbitMqConstants.SC_ERP_ADD_QUEUE, result.toString());
            serviceHelper.getRabbitMqManager().basicPublish(RabbitMqConstants.SC_ERP_EXCHANGE, RabbitMqConstants.SC_TO_ERP_CRM_QUEUE_NAME, RabbitMqConstants.SC_ERP_ADD_QUEUE, null, result.toString().getBytes());

            // 修改当前数据状态为待审核
            serviceHelper.getAdvantageModelMapper().updateAuditStatus(advantageModelApplyDelayVo.getId(), AuditStatusEnum.PENDING.getScStatusCode());
        }

        serviceResult.setMessage(ServiceResult.INSERT_SUCCESS);
        serviceResult.setSuccess(Boolean.TRUE);
        serviceResult.setResult(Boolean.TRUE);
        return serviceResult;
    }

    /**
     * 优势型号单条新增
     * @param advantageModelAddVo 优势型号单条新增的Vo类
     * @param authenticationUser  用户信息
     * @return 返回新增结果
     */
    @Override
    public ServiceResult<Boolean> add(AdvantageModelAddVo advantageModelAddVo, AuthenticationUser authenticationUser, Integer source) throws IOException, ParseException {
        ServiceResult<Boolean> serviceResult = new ServiceResult<>();

        AdvantageModel advantageModel = new AdvantageModel();
        BeanUtils.copyProperties(advantageModelAddVo, advantageModel);
        advantageModel.setAuditStatus(AuditStatusEnum.PENDING.getScStatusCode());
        advantageModel.setAdvantageStatus(AdvantageStatusEnum.INVALID.getScStatusCode());
        advantageModel.setCreateUser(authenticationUser.getUsername());
        advantageModel.setCreateUserId(authenticationUser.getId());
        advantageModel.setCreateDate(new Date(System.currentTimeMillis()));
        advantageModel.setEnterpriseId(authenticationUser.getEpId());
        advantageModel.setSource(source);

        // 处理有效期
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        advantageModel.setValidityDateStart(sdf.parse(advantageModelAddVo.getValidityDateStart()));
        advantageModel.setValidityDateEnd(sdf.parse(advantageModelAddVo.getValidityDateEnd()));

        int insert = serviceHelper.getAdvantageModelMapper().insert(advantageModel);
        if(insert > 0){
            log.info("优势型号数据新增成功,新增的数据id为:[{}]", advantageModel.getId());

            // 推送mq消息到erp新增优势型号信息
            sendMqMsgToErpAddAdvantageModel(advantageModel);
        }

        serviceResult.setMessage(ServiceResult.INSERT_SUCCESS);
        serviceResult.setSuccess(Boolean.TRUE);
        serviceResult.setResult(Boolean.TRUE);
        return serviceResult;
    }

    /**
     * 优势型号批量导入
     * @param advantageModelBatchAddVo 优势型号批量导入的Vo类
     * @param authenticationUser 用户信息
     * @return 返回导入结果
     */
    @Override
    public ServiceResult<AdvantageModelBatchAddExceptionRespPojo> batchAdd(AdvantageModelBatchAddVo advantageModelBatchAddVo, AuthenticationUser authenticationUser) throws IOException, ParseException {
        AdvantageModelBatchAddExceptionRespPojo result = new AdvantageModelBatchAddExceptionRespPojo();

        // 待审核数据数量
        Integer reviewedDataCount = 0;

        // 待审核数据
        List<AdvantageModelBatchAddRespPojo> reviewedData = new ArrayList<>();

        // 已审核通过的数据数量
        Integer approvedDataCount = 0;

        // 已审核通过的数据
        List<AdvantageModelBatchAddRespPojo> approvedData = new ArrayList<>();

        // 库存不存在的数据数量
        Integer inventoryNoHaveDataCount = 0;

        // 库存不存在的数据
        List<AdvantageModelBatchAddRespPojo> inventoryNoHaveData = new ArrayList<>();


        for(AdvantageModelBatchAddParamVo advantageModelBatchAddParamVo : advantageModelBatchAddVo.getList()){
            // 根据型号、品牌查询优势型号表
            QueryWrapper<AdvantageModel> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq(AdvantageModelConstants.PART_NUMBER_FIELD, advantageModelBatchAddParamVo.getPartNumber());
            queryWrapper.eq(AdvantageModelConstants.BRAND_FIELD, advantageModelBatchAddParamVo.getBrand());
            queryWrapper.eq(Constants.ENTERPRISE_ID_FIELD, authenticationUser.getEpId());
            List<AdvantageModel> advantageModels = serviceHelper.getAdvantageModelMapper().selectList(queryWrapper);
            if(advantageModels != null && advantageModels.size() > 0){
                AdvantageModel advantageModel = advantageModels.get(0);

                // 已存在并生效的型号跳过处理
                if(advantageModel.getAdvantageStatus() != null && advantageModel.getAdvantageStatus().toString().equals(AdvantageStatusEnum.EFFECTIVE.getScStatusCode().toString())){
                    approvedDataCount++;
                    AdvantageModelBatchAddRespPojo advantageModelBatchAddRespPojo = new AdvantageModelBatchAddRespPojo();
                    BeanUtils.copyProperties(advantageModelBatchAddParamVo, advantageModelBatchAddRespPojo);
                    approvedData.add(advantageModelBatchAddRespPojo);

                    // 更新备注信息
                    updateRemark(advantageModel.getId(), advantageModelBatchAddParamVo.getRemark());
                    continue;
                }

                // 已存在状态为失效的型号数据，将审核状态修改为待审核，推送mq消息到erp
                if(advantageModel.getAdvantageStatus() != null && advantageModel.getAdvantageStatus().toString().equals(AdvantageStatusEnum.INVALID.getScStatusCode().toString())){
                    reviewedDataCount++;
                    AdvantageModelBatchAddRespPojo advantageModelBatchAddRespPojo = new AdvantageModelBatchAddRespPojo();
                    BeanUtils.copyProperties(advantageModelBatchAddParamVo, advantageModelBatchAddRespPojo);
                    reviewedData.add(advantageModelBatchAddRespPojo);

                    serviceHelper.getAdvantageModelMapper().updateAuditStatus(advantageModel.getId(), AuditStatusEnum.PENDING.getScStatusCode());

                    // 更新备注信息
                    updateRemark(advantageModel.getId(), advantageModelBatchAddParamVo.getRemark());

                    // 推送mq消息到erp修改优势型号的审核状态
                    SpecialsScTopViewAuditPojo specialsScTopViewAuditPojo = new SpecialsScTopViewAuditPojo();
                    specialsScTopViewAuditPojo.setEnterpriseID(advantageModel.getEnterpriseId());
                    specialsScTopViewAuditPojo.setPartNumber(advantageModel.getPartNumber());
                    specialsScTopViewAuditPojo.setBrand(advantageModel.getBrand());
                    specialsScTopViewAuditPojo.setStartDate(advantageModel.getValidityDateStart());
                    specialsScTopViewAuditPojo.setEndDate(advantageModel.getValidityDateEnd());
                    specialsScTopViewAuditPojo.setStatus(AuditStatusEnum.PENDING.getErpStatusCode());
                    JSONObject json = (JSONObject) JSONObject.toJSON(specialsScTopViewAuditPojo);

                    // 包装发送到rabbitmq的消息内容
                    JSONObject jsonObject = serviceHelper.packageSendRabbitMqMsgData(json, RabbitMqConstants.SC_ERP_AUDIT_QUEUE);

                    log.info("推送给rabbitmq的交换机:[{}],队列:[{}]的消息内容为:[{}]", RabbitMqConstants.SC_ERP_EXCHANGE, RabbitMqConstants.SC_ERP_AUDIT_QUEUE, jsonObject.toString());
                    serviceHelper.getRabbitMqManager().basicPublish(RabbitMqConstants.SC_ERP_EXCHANGE, RabbitMqConstants.SC_TO_ERP_CRM_QUEUE_NAME, RabbitMqConstants.SC_ERP_AUDIT_QUEUE, null, result.toString().getBytes());
                }
            }else{
                // 根据品牌、型号查询库存数据
                Map<String, Object> param = new HashMap<>();
                param.put(AdvantageModelConstants.PART_NUMBER, advantageModelBatchAddParamVo.getPartNumber());
                param.put(AdvantageModelConstants.BRAND_FIELD, advantageModelBatchAddParamVo.getBrand());
                param.put(Constants.ENTERPRISE_ID, authenticationUser.getEpId());
                int count = serviceHelper.getInventoryMapper().selectCountByParam(param);
                if(count > 0){
                    // 添加优势型号数据，状态为待审核，推送mq消息到erp
                    AdvantageModel advantageModel = new AdvantageModel();
                    advantageModel.setPartNumber(advantageModelBatchAddParamVo.getPartNumber());
                    advantageModel.setBrand(advantageModelBatchAddParamVo.getBrand());
                    advantageModel.setAuditStatus(AuditStatusEnum.PENDING.getScStatusCode());
                    advantageModel.setAdvantageStatus(AdvantageStatusEnum.INVALID.getScStatusCode());
                    advantageModel.setCreateUser(authenticationUser.getUsername());
                    advantageModel.setCreateUserId(authenticationUser.getId());
                    advantageModel.setCreateDate(new Date(System.currentTimeMillis()));
                    advantageModel.setEnterpriseId(authenticationUser.getEpId());
                    advantageModel.setRemark(advantageModelBatchAddParamVo.getRemark());
                    advantageModel.setSource(AdvantageModelSourceEnum.USER_ADD.getCode());
                    // 处理有效期
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    advantageModel.setValidityDateStart(sdf.parse(advantageModelBatchAddVo.getValidityDateStart()));
                    advantageModel.setValidityDateEnd(sdf.parse(advantageModelBatchAddVo.getValidityDateEnd()));
                    int insert = serviceHelper.getAdvantageModelMapper().insert(advantageModel);
                    if(insert > 0){
                        // 推送mq消息到erp新增优势型号信息
                        sendMqMsgToErpAddAdvantageModel(advantageModel);
                    }
                }else{
                    inventoryNoHaveDataCount++;
                    AdvantageModelBatchAddRespPojo advantageModelBatchAddRespPojo = new AdvantageModelBatchAddRespPojo();
                    advantageModelBatchAddRespPojo.setTableName(advantageModelBatchAddParamVo.getTableName());
                    advantageModelBatchAddRespPojo.setPartNumber(advantageModelBatchAddParamVo.getPartNumber());
                    advantageModelBatchAddRespPojo.setBrand(advantageModelBatchAddParamVo.getBrand());
                    inventoryNoHaveData.add(advantageModelBatchAddRespPojo);
                }
            }
        }

        result.setReviewedDataCount(reviewedDataCount);
        result.setReviewedData(reviewedData);
        result.setApprovedDataCount(approvedDataCount);
        result.setApprovedData(approvedData);
        result.setInventoryNoHaveDataCount(inventoryNoHaveDataCount);
        result.setInventoryNoHaveData(inventoryNoHaveData);

        ServiceResult<AdvantageModelBatchAddExceptionRespPojo> serviceResult = new ServiceResult<>();
        serviceResult.setMessage(ServiceResult.IMPORT_SUCCESS);
        serviceResult.setSuccess(Boolean.TRUE);
        serviceResult.setResult(result);
        return serviceResult;
    }

    /**
     * 更新备注信息
     * @param id 优势型号id
     * @param remark 备注
     */
    private void updateRemark(Integer id, String remark){
        if(!Strings.isNullOrEmpty(remark)){
            UpdateWrapper<AdvantageModel> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq(Constants.ID, id);

            AdvantageModel entity = new AdvantageModel();
            entity.setRemark(remark);
            serviceHelper.getAdvantageModelMapper().update(entity, updateWrapper);
        }
    }

    /**
     * 查询拒绝原因
     * @param id 主键id
     * @return 返回拒绝原因
     */
    @Override
    public ServiceResult<String> queryRefusedReason(String id) {
        ServiceResult<String> serviceResult = new ServiceResult<>();

        String result = serviceHelper.getAdvantageModelMapper().queryRefusedReason(id);

        serviceResult.setMessage(ServiceResult.SELECT_SUCCESS);
        serviceResult.setSuccess(Boolean.TRUE);
        serviceResult.setResult(result);
        return serviceResult;
    }

    /**
     * 优势型号信息列表查询
     * @param advantageModelRequestVo 优势型号信息列表查询的请求Vo类
     * @param enterpriseId 供应商id
     * @return 返回优势型号信息
     */
    @Override
    public ServiceResult<List<AdvantageModelRespPojo>> query(AdvantageModelRequestVo advantageModelRequestVo, String enterpriseId) {
        ServiceResult<List<AdvantageModelRespPojo>> serviceResult = new ServiceResult<>();

        advantageModelRequestVo.setPageNo((advantageModelRequestVo.getPageNo() - 1) * advantageModelRequestVo.getPageSize());

        // 优势型号信息列表查询
        List<AdvantageModelRespPojo> list = serviceHelper.getAdvantageModelMapper().query(advantageModelRequestVo, enterpriseId);

        serviceResult.setMessage(ServiceResult.SELECT_SUCCESS);
        serviceResult.setSuccess(Boolean.TRUE);
        serviceResult.setResult(list);
        return serviceResult;
    }

    /**
     * 优势型号信息数据数量查询
     * @param advantageModelRequestVo 优势型号信息列表查询的请求Vo类
     * @param enterpriseId 供应商id
     * @return 返回优势型号信息
     */
    @Override
    public ServiceResult<Long> queryTotal(AdvantageModelRequestVo advantageModelRequestVo, String enterpriseId) {
        ServiceResult<Long> serviceResult = new ServiceResult<>();

        // 优势型号信息列表查询
        Long result = serviceHelper.getAdvantageModelMapper().queryTotal(advantageModelRequestVo, enterpriseId);

        serviceResult.setMessage(ServiceResult.SELECT_SUCCESS);
        serviceResult.setSuccess(Boolean.TRUE);
        serviceResult.setResult(result);
        return serviceResult;
    }

    /**
     * 取消优势型号
     * @param advantageModelCancleVo 取消优势型号的Vo类
     * @param enterpriseId 供应商id
     * @return 返回处理结果
     */
    @Override
    public ServiceResult<Boolean> cancleAdvantageModel(AdvantageModelCancleVo advantageModelCancleVo, String enterpriseId) throws IOException {
        ServiceResult<Boolean> serviceResult = new ServiceResult<>();

        // 全部取消优势型号
        if(advantageModelCancleVo.getIsAll() != null && advantageModelCancleVo.getIsAll()){
            Map<String, String> map = new HashMap<>();
            map.put(AdvantageModelConstants.PART_NUMBER, advantageModelCancleVo.getPartNumber());
            map.put(AdvantageModelConstants.BRAND_FIELD, advantageModelCancleVo.getBrand());
            map.put(AdvantageModelConstants.CREATE_USER, advantageModelCancleVo.getCreateUser());
            map.put(AdvantageModelConstants.AUDIT_STATUS, advantageModelCancleVo.getAuditStatus());
            map.put(AdvantageModelConstants.ADVANTAGE_STATUS, advantageModelCancleVo.getAdvantageStatus());
            map.put(Constants.ENTERPRISE_ID, enterpriseId);

            // 根据查询条件获取需要取消优势型号的数据id
            List<Integer> idList = serviceHelper.getAdvantageModelMapper().selectCancleDataIdList(map);
            if(idList != null && idList.size() > 0){
                for(Integer id : idList){
                    // 更新优势型号状态，推送mq消息
                    updateAdvantageModelStatusSendMqMsg(id, enterpriseId);
                }
            }
        }else{
            for(Integer id : advantageModelCancleVo.getIdList()){
                // 更新优势型号状态，推送mq消息
                updateAdvantageModelStatusSendMqMsg(id, enterpriseId);
            }
        }

/*        for(Integer id : advantageModelCancleVo.getIdList()){
            // 更新优势型号状态，推送mq消息
            updateAdvantageModelStatusSendMqMsg(id, enterpriseId);
        }*/

        serviceResult.setSuccess(Boolean.TRUE);
        serviceResult.setResult(Boolean.TRUE);
        serviceResult.setMessage(ServiceResult.OPERATE_SUCCESS);
        return serviceResult;
    }

    /**
     * 更新优势型号状态，推送mq消息
     * @param id 优势型号id
     * @param enterpriseId 供应商id
     */
    private void updateAdvantageModelStatusSendMqMsg(Integer id, String enterpriseId) throws IOException {
        // 判断当前型号的品牌是否为优势品牌且有库存，为优势品牌且有库存时不允许取消优势型号
        Boolean aBoolean = judgeIfAdvantageBrandHaveInventory(id, enterpriseId);
        if(aBoolean){
            log.info("取消优势型号的优势型号:[{}]的品牌是优势品牌且有库存,无法取消优势型号", id);
            return;
        }

        // 取消优势型号
        int i = serviceHelper.getAdvantageModelMapper().updateAdvantageModelStatus(id, AdvantageStatusEnum.INVALID.getScStatusCode());
        if(i > 0){
            AdvantageModel advantageModel = serviceHelper.getAdvantageModelMapper().selectById(id);
            if(advantageModel != null){
                // 删除redis中的优势型号信息
                deleteAdvantageModelFromRedis(advantageModel);

                // 取消优势型号推送mq消息
                cancleAdvantageModelSendMqMsg(advantageModel.getErpId());
            }
        }
    }

    /**
     * 查询可申请优势型号的的库存型号
     * @param epId 供应商id
     * @return 返回可申请优势型号的的库存型号
     */
    @Override
    public ServiceResult<List<MayApplyInventoryModelPojo>> getMayApplyInventoryModel(String epId) {
        ServiceResult<List<MayApplyInventoryModelPojo>> serviceResult = new ServiceResult<>();

        List<MayApplyInventoryModelPojo> result = new ArrayList<>();

        // 查询当前供应商去重后的库存型号
        List<Inventory> inventories = serviceHelper.getInventoryMapper().selectDistinctInventoryList(epId);
        if(inventories != null && inventories.size() > 0){
            // 通过redis查询当前供应商已申请的优势型号信息
            String key = RedisKeyPrefixEnum.ADVANTAGE_MODEL_DATA.getCode() + "_*_" + epId;
            List<String> list = serviceHelper.getRedisManager().keysFuzzy(key);
            List<AdvantageModel> advantageModels = convertAdvantageModelList(list);
            // 获取可申请优势型号的的库存型号
            result = getMayApplyInventoryModelList(inventories, advantageModels);
        }

        serviceResult.setSuccess(Boolean.TRUE);
        serviceResult.setResult(result);
        serviceResult.setMessage(ServiceResult.SELECT_SUCCESS);
        return serviceResult;
    }

    /**
     * 将优势型号字符串集合为实体集合
     * @param list 优势型号字符串集合
     * @return 返回处理结果
     */
    private List<AdvantageModel> convertAdvantageModelList(List<String> list){
        List<AdvantageModel> result = new ArrayList<>();
        if(list != null && list.size() > 0){
            for(String advantageStr : list){
                AdvantageModel advantageModel = JSONObject.toJavaObject(JSON.parseObject(advantageStr), AdvantageModel.class);
                result.add(advantageModel);
            }
        }
        return result;
    }

    /**
     * 优势型号信息删除
     * @param advantageModelDeleteVo 删除数据的Vo类
     * @param enterpriseId 供应商id
     * @return 返回删除结果信息
     */
    @Override
    public ServiceResult<Boolean> delete(AdvantageModelDeleteVo advantageModelDeleteVo, String enterpriseId) throws IOException {
        ServiceResult<Boolean> serviceResult = new ServiceResult<>();

        String message = ServiceResult.DELETE_FAIL;
        boolean result = Boolean.FALSE;
        int count = 0;

        // 全部删除优势型号
        if(advantageModelDeleteVo.getIsAll() != null && advantageModelDeleteVo.getIsAll()) {
            Map<String, String> map = new HashMap<>();
            map.put(AdvantageModelConstants.PART_NUMBER, advantageModelDeleteVo.getPartNumber());
            map.put(AdvantageModelConstants.BRAND_FIELD, advantageModelDeleteVo.getBrand());
            map.put(AdvantageModelConstants.CREATE_USER, advantageModelDeleteVo.getCreateUser());
            map.put(AdvantageModelConstants.AUDIT_STATUS, advantageModelDeleteVo.getAuditStatus());
            map.put(AdvantageModelConstants.ADVANTAGE_STATUS, advantageModelDeleteVo.getAdvantageStatus());
            map.put(Constants.ENTERPRISE_ID, enterpriseId);

            // 根据查询条件获取需要删除优势型号的数据id
            List<Integer> idList = serviceHelper.getAdvantageModelMapper().selectIdListByParam(map);
            if(idList != null && idList.size() > 0) {
                for (Integer id : idList) {
                    int i = deleteAdvantageModelSendMsg(id, enterpriseId);
                    if(i > 0){
                        count++;
                        message = ServiceResult.DELETE_SUCCESS;
                        result = Boolean.TRUE;
                    }
                }
            }
        }else{
            for(Integer id : advantageModelDeleteVo.getIdList()){
                int i = deleteAdvantageModelSendMsg(id, enterpriseId);
                if(i > 0){
                    count++;
                    message = ServiceResult.DELETE_SUCCESS;
                    result = Boolean.TRUE;
                }
            }
        }

/*        for(Integer id : advantageModelDeleteVo.getIdList()){
            int i = deleteAdvantageModelSendMsg(id, enterpriseId);
            if(i > 0){
                count++;
                message = ServiceResult.DELETE_SUCCESS;
                result = Boolean.TRUE;
            }
        }*/

        // 所有数据均无法提交审核时返回信息给前端响应
        if(count == 0){
            message = "删除的数据均为优势品牌且有库存,无法删除,请知悉";
        }

        serviceResult.setSuccess(Boolean.TRUE);
        serviceResult.setResult(result);
        serviceResult.setMessage(message);
        return serviceResult;
    }

    /**
     * 删除优势型号，推送mq消息
     * @param id 优势型号id
     * @param enterpriseId 供应商id
     * @return 返回删除结果
     */
    private int deleteAdvantageModelSendMsg(Integer id, String enterpriseId) throws IOException {
        // 判断当前型号的品牌是否为优势品牌且有库存，为优势品牌且有库存时不允许删除
        Boolean aBoolean = judgeIfAdvantageBrandHaveInventory(id, enterpriseId);
        if(aBoolean){
            log.info("删除的优势型号:[{}]的品牌是优势品牌且有库存,无法删除", id);
            return 0;
        }

        // 推送mq消息到erp
        AdvantageModel advantageModel = serviceHelper.getAdvantageModelMapper().selectById(id);
        if(advantageModel != null){
            // 从redis中删除优势型号信息
            deleteAdvantageModelFromRedis(advantageModel);

            JSONObject json = new JSONObject();
            json.put(AdvantageConstants.ID, advantageModel.getErpId());

            // 包装发送到rabbitmq的消息内容
            JSONObject result = serviceHelper.packageSendRabbitMqMsgData(json, RabbitMqConstants.SC_ERP_DEL_QUEUE);

            log.info("推送给rabbitmq的交换机:[{}],队列:[{}]的消息内容为:[{}]", RabbitMqConstants.SC_ERP_EXCHANGE, RabbitMqConstants.SC_ERP_DEL_QUEUE, result.toString());
            serviceHelper.getRabbitMqManager().basicPublish(RabbitMqConstants.SC_ERP_EXCHANGE, RabbitMqConstants.SC_TO_ERP_CRM_QUEUE_NAME, RabbitMqConstants.SC_ERP_DEL_QUEUE, null, result.toString().getBytes());
        }

        // 删除优势型号信息
        int i = serviceHelper.getAdvantageModelMapper().deleteById(id);
        if(i > 0){
            return 1;
        }
        return 0;
    }

    /**
     * 清空表SpecialsSCTopView中的全部数据
     */
    @Override
    public void truncateTable() {
        serviceHelper.getAdvantageModelMapper().truncateTable();
    }

    /**
     * 优势品牌删除时,同时删除品牌下的型号,只删除状态为2
     * @param specialsScTopViewCloseDelPojo 取消优势型号的pojo类
     */
    @Override
    public void deleteByRelationModel(SpecialsScTopViewCloseDelPojo specialsScTopViewCloseDelPojo) throws IOException {
        if (!StringUtils.validateParameter(specialsScTopViewCloseDelPojo.getBrand())) {
            return;
        }
        Map<String, Object> param = new HashMap<>();
        param.put("enterprise_id", specialsScTopViewCloseDelPojo.getEnterpriseID());
        param.put("brand", specialsScTopViewCloseDelPojo.getBrand());
        param.put("source", AdvantageModelSourceEnum.ADVANTAGE_BRAND_ASSOCIATED.getCode());
        List<AdvantageModel> advantageModels = this.baseMapper.selectByMap(param);
        if (advantageModels == null || advantageModels.size() == 0) {
            return;
        }
        List<Integer> ids = advantageModels.stream().map(AdvantageModel::getId).distinct().collect(Collectors.toList());

        AdvantageModelDeleteVo advantageModelDeleteVo = new AdvantageModelDeleteVo();
        advantageModelDeleteVo.setIdList(ids);
        this.delete(advantageModelDeleteVo, specialsScTopViewCloseDelPojo.getEnterpriseID());
    }

    @Override
    public void cancelAdvantageBrand(SpecialsScTopViewCloseDelPojo specialsScTopViewCloseDelPojo) throws IOException {
        if (!StringUtils.validateParameter(specialsScTopViewCloseDelPojo.getBrand())) {
            return;
        }
        Map<String, Object> param = new HashMap<>();
        param.put("enterprise_id", specialsScTopViewCloseDelPojo.getEnterpriseID());
        param.put("brand", specialsScTopViewCloseDelPojo.getBrand());
        param.put("source", AdvantageModelSourceEnum.ADVANTAGE_BRAND_ASSOCIATED.getCode());
        List<AdvantageModel> advantageModels = this.baseMapper.selectByMap(param);
        if (advantageModels == null || advantageModels.size() == 0) {
            return;
        }
        List<Integer> ids = advantageModels.stream().map(AdvantageModel::getId).distinct().collect(Collectors.toList());
        AdvantageModelCancleVo advantageModelCancleVo = new AdvantageModelCancleVo();
        advantageModelCancleVo.setIdList(ids);
        this.cancleAdvantageModel(advantageModelCancleVo, specialsScTopViewCloseDelPojo.getEnterpriseID());
    }

    /**
     * 根据供应商id、品牌、型号查询sc的优势型号信息
     * @param enterpriseID 供应商id
     * @param partNumber 型号
     * @param brand 品牌
     * @return 返回优势型号信息
     */
    private List<Inventory> selectAdvantageModelDataByEpIdPartNoBrand(String enterpriseID, String partNumber, String brand) {
        QueryWrapper<Inventory> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(Constants.ENTERPRISE_ID_FIELD, enterpriseID);
        queryWrapper.eq(AdvantageModelConstants.PART_NUMBER_FIELD, partNumber);
        queryWrapper.eq(AdvantageModelConstants.BRAND_FIELD, brand);
        List<Inventory> inventorys = serviceHelper.getInventoryMapper().selectList(queryWrapper);
        if(inventorys != null && inventorys.size() > 0){
            return inventorys;
        }
        return null;
    }

    /**
     * 更新优势型号信息
     * @param ifAuditData 是否是审批消息
     * @param model 优势型号数据
     * @param specialsScTopView 优势型号信息
     */
    private void updateAdvantageModel(boolean ifAuditData, Inventory model, SpecialsSCTopView specialsScTopView) {
        Inventory inventory = new SpecialsSCTopView().toAdvantageModel(specialsScTopView, AuditStatusEnum.getScStatusCode(specialsScTopView.getAuditStatus()), AdvantageStatusEnum.getScStatusCode(specialsScTopView.getAuditStatus()));
        inventory.setId(model.getId());
        inventory.setSource(AdvantageModelSourceEnum.ERP_IMPORT.getCode());
        int i = serviceHelper.getInventoryMapper().updateAdvantageModel(inventory);
        if(i > 0){
            // 审批通过
            if(ifAuditData && inventory.getAuditStatus().intValue() == AuditStatusEnum.APPROVE.getScStatusCode().intValue()){
                String content = "恭喜您，您的优势型号(" + model.getPartNumber() + ")已通过审核";
                List<String> userIds = new ArrayList<>();
                userIds.add(model.getCreateUserId());
                saveActionMessage(content, userIds);
            }

            // 审批拒绝
            if(ifAuditData && inventory.getAuditStatus().intValue() == AuditStatusEnum.APPROVAL_REFUSED.getScStatusCode().intValue()){
                String content = "很遗憾，您的优势型号(" + model.getPartNumber() + ")申请被拒绝";
                List<String> userIds = new ArrayList<>();
                userIds.add(model.getCreateUserId());
                saveActionMessage(content, userIds);
            }
        }
    }

    /**
     * 保存动作消息
     * @param content 消息内容
     * @param userIds 接收消息的用户
     */
    private void saveActionMessage(String content, List<String> userIds){
        if(userIds != null && userIds.size() > 0){
            ActionMessage actionMessage = new ActionMessage();
            actionMessage.setContent(content);
            actionMessage.setCreateTime(new Date());
            ServiceResult serviceResult = actionMessageService.handleActionMessage(actionMessage, userIds);
            if(serviceResult != null && serviceResult.getSuccess()){
                log.info("动作消息保存成功,消息内容为:[{}],接收消息的用户为:[{}]", content, userIds);
            }
        }
    }

    /**
     * 推送mq消息到erp新增优势型号信息
     * @param advantageModel 优势型号信息
     */
    private void sendMqMsgToErpAddAdvantageModel(AdvantageModel advantageModel) throws IOException {
        if(advantageModel != null){
            SpecialsScTopViewAddPojo specialsScTopViewAddPojo = new SpecialsScTopViewAddPojo();
            specialsScTopViewAddPojo.setEnterpriseID(advantageModel.getEnterpriseId());
            specialsScTopViewAddPojo.setType(advantageModel.getType());
            specialsScTopViewAddPojo.setPartNumber(advantageModel.getPartNumber());
            specialsScTopViewAddPojo.setBrand(advantageModel.getBrand());
            specialsScTopViewAddPojo.setStartDate(advantageModel.getValidityDateStart());
            specialsScTopViewAddPojo.setEndDate(advantageModel.getValidityDateEnd());
            specialsScTopViewAddPojo.setCreator(advantageModel.getCreateUser());
            specialsScTopViewAddPojo.setSummary(advantageModel.getRemark());
            JSONObject json = (JSONObject) JSONObject.toJSON(specialsScTopViewAddPojo);

            // 包装发送到rabbitmq的消息内容
            JSONObject result = serviceHelper.packageSendRabbitMqMsgData(json, RabbitMqConstants.SC_ERP_ADD_QUEUE);

            log.info("推送给rabbitmq的交换机:[{}],队列:[{}]的消息内容为:[{}]", RabbitMqConstants.SC_ERP_EXCHANGE, RabbitMqConstants.SC_ERP_ADD_QUEUE, result.toString());
            serviceHelper.getRabbitMqManager().basicPublish(RabbitMqConstants.SC_ERP_EXCHANGE, RabbitMqConstants.SC_TO_ERP_CRM_QUEUE_NAME, RabbitMqConstants.SC_ERP_ADD_QUEUE, null, result.toString().getBytes());
        }
    }

    /**
     * 校验当前优势型号数据是否为审核拒绝或审核通过且状态为无效的数据
     * @param id 优势型号数据id
     * @return 返回校验结果
     */
    private Boolean checkAdvantageModelStatusIfInvalid(Integer id) {
        AdvantageModel advantageModel = serviceHelper.getAdvantageModelMapper().selectById(id);
        if(advantageModel != null){
            // 判断优势型号数据是否为审核拒绝状态
            if(advantageModel.getAuditStatus() != null && advantageModel.getAuditStatus().intValue() == AuditStatusEnum.APPROVAL_REFUSED.getScStatusCode().intValue()){
                log.info("当前优势型号(id:[{}])数据为审核拒绝状态", id);
                return Boolean.TRUE;
            }

            // 判断优势型号数据是否为审核通过且状态为无效数据
            if(advantageModel.getAuditStatus() != null && advantageModel.getAuditStatus().intValue() == AuditStatusEnum.APPROVE.getScStatusCode().intValue()
                    && advantageModel.getAdvantageStatus().intValue() == AdvantageStatusEnum.INVALID.getScStatusCode().intValue()){
                log.info("当前优势型号(id:[{}])数据为审核通过且状态为无效", id);
                return Boolean.TRUE;
            }

        }
        return Boolean.FALSE;
    }

    /**
     * 判断是否为优势型号
     * @param brand 品牌
     * @param partNumber 型号
     * @param needGoodsCount 需要的货物数量
     * @return 返回结果
     */
    private List<AdvantageModelJudgeStatusRespPojo> judgeIfAdvantageModel(String brand, String partNumber, Integer needGoodsCount){
        List<AdvantageModelJudgeStatusRespPojo> result = new ArrayList<>();

        // 根据创建用户分组查询优势型号数据
        Map<String, Object> map = new HashMap<>();
        map.put(AdvantageModelConstants.BRAND_FIELD, brand);
        map.put(AdvantageModelConstants.PART_NUMBER_FIELD, partNumber);
        List<AdvantageModelGroupByUserPojo> advantageModels = serviceHelper.getAdvantageModelMapper().selecAdvantageModeltListGroupByUser(map);
        if(advantageModels != null && advantageModels.size() > 0){
            for(AdvantageModelGroupByUserPojo advantageModelGroupByUserPojo : advantageModels){
                AdvantageModelJudgeStatusRespPojo advantageModelJudgeStatusRespPojo = new AdvantageModelJudgeStatusRespPojo();
                BeanUtils.copyProperties(advantageModelGroupByUserPojo, advantageModelJudgeStatusRespPojo);
                // 型号是否优势
                if(advantageModelGroupByUserPojo.getAuditStatus().intValue() == AuditStatusEnum.APPROVE.getScStatusCode()
                        && advantageModelGroupByUserPojo.getAdvantageStatus().intValue() == AdvantageStatusEnum.EFFECTIVE.getScStatusCode().intValue()){
                    advantageModelJudgeStatusRespPojo.setModelIfAdvantage(Boolean.TRUE);
                }else{
                    advantageModelJudgeStatusRespPojo.setModelIfAdvantage(Boolean.FALSE);
                }

                // 判断品牌是否优势
                advantageModelJudgeStatusRespPojo.setBrandIfAdvantage(judgeBrandIfAdvantage(advantageModelGroupByUserPojo.getBrand(), advantageModelGroupByUserPojo.getUserId(), advantageModelGroupByUserPojo.getEnterpriseId()));

                // 库存结果
                if(needGoodsCount != null){
                    QueryWrapper<Inventory> inventoryParam = new QueryWrapper<>();
                    inventoryParam.eq(AdvantageModelConstants.BRAND_FIELD, brand);
                    inventoryParam.eq(AdvantageModelConstants.PART_NUMBER_FIELD, partNumber);
                    inventoryParam.eq(Constants.ENTERPRISE_ID_FIELD, advantageModelGroupByUserPojo.getEnterpriseId());
                    inventoryParam.eq(Constants.STATUS_, InventoryStatusEnum.SHELVES.getCode());
                    List<Inventory> inventories = serviceHelper.getInventoryMapper().selectList(inventoryParam);
                    if(inventories != null && inventories.size() > 0){
                        // 判断库存是否充足
                        for(Inventory inventory : inventories){
                            if(inventory.getCount().equals(needGoodsCount) || inventory.getCount() > needGoodsCount){
                                advantageModelJudgeStatusRespPojo.setInventoryResult(InventoryResultEnum.SUFFICIENT.getCode());
                                break;
                            }
                        }

                        // 有库存数据但是无库存结果，返回库存不足
                        if(advantageModelJudgeStatusRespPojo.getInventoryResult() == null){
                            advantageModelJudgeStatusRespPojo.setInventoryResult(InventoryResultEnum.INSUFFICIENT.getCode());
                        }
                    }else{
                        // 无库存
                        advantageModelJudgeStatusRespPojo.setInventoryResult(InventoryResultEnum.NO_HAVE.getCode());
                    }
                }
                result.add(advantageModelJudgeStatusRespPojo);
            }
        }
        return result;
    }

    /**
     * 判断品牌是否优势
     * @param brand 品牌
     * @param createUserId 创建人
     * @param enterpriseId 供应商id
     * @return 返回判断结果
     */
    private boolean judgeBrandIfAdvantage(String brand, String createUserId, String enterpriseId){
        boolean result = Boolean.FALSE;

        if(Strings.isNullOrEmpty(brand) || Strings.isNullOrEmpty(createUserId)){
            return Boolean.FALSE;
        }

        QueryWrapper<AdvantageBrand> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(AdvantageModelConstants.BRAND_FIELD, brand);
        queryWrapper.eq(Constants.ENTERPRISE_ID_FIELD, enterpriseId);
        List<AdvantageBrand> advantageBrands = serviceHelper.getAdvantageBrandMapper().selectList(queryWrapper);
        if(advantageBrands != null && advantageBrands.size() > 0){
            for(AdvantageBrand advantageBrand : advantageBrands){
                if(advantageBrand.getAuditStatus() != null && advantageBrand.getAdvantageStatus() != null
                        && advantageBrand.getAuditStatus().intValue() == AuditStatusEnum.APPROVE.getScStatusCode()
                        && advantageBrand.getAdvantageStatus().intValue() == AdvantageStatusEnum.EFFECTIVE.getScStatusCode().intValue()){
                    result = Boolean.TRUE;
                    break;
                }
            }
        }
        return result;
    }

    /**
     * 判断是否为优势型号
     * @param partNumber 型号
     * @return 返回结果
     */
    private List<AdvantageModelJudgeModelStatusRespPojo> judgeIfAdvantageModelByPartNumber(String partNumber){
        List<AdvantageModelJudgeModelStatusRespPojo> result = new ArrayList<>();

        // 根据创建用户分组查询优势型号数据
        Map<String, Object> map = new HashMap<>();
        map.put(AdvantageModelConstants.PART_NUMBER_FIELD, partNumber);
        List<AdvantageModelGroupByUserPojo> advantageModels = serviceHelper.getAdvantageModelMapper().selecAdvantageModeltListGroupByUser(map);
        if(advantageModels != null && advantageModels.size() > 0){
            for(AdvantageModelGroupByUserPojo advantageModelGroupByUserPojo : advantageModels){
                AdvantageModelJudgeModelStatusRespPojo advantageModelJudgeModelStatusRespPojo = new AdvantageModelJudgeModelStatusRespPojo();
                BeanUtils.copyProperties(advantageModelGroupByUserPojo, advantageModelJudgeModelStatusRespPojo);
                // 型号是否优势
                if(advantageModelGroupByUserPojo.getAuditStatus().intValue() == AuditStatusEnum.APPROVE.getScStatusCode()
                        && advantageModelGroupByUserPojo.getAdvantageStatus().intValue() == AdvantageStatusEnum.EFFECTIVE.getScStatusCode().intValue()){
                    advantageModelJudgeModelStatusRespPojo.setModelIfAdvantage(Boolean.TRUE);
                }else{
                    advantageModelJudgeModelStatusRespPojo.setModelIfAdvantage(Boolean.FALSE);
                }
                result.add(advantageModelJudgeModelStatusRespPojo);
            }
        }
        return result;
    }

    /**
     * 判断当前型号的品牌是否为优势品牌且有库存，为优势品牌且有库存时不允许删除
     * @param id 优势型号id
     * @param enterpriseId 供应商id
     * @return 返回判断结果
     */
    private Boolean judgeIfAdvantageBrandHaveInventory(Integer id, String enterpriseId) {
        boolean result = Boolean.FALSE;

        AdvantageModel advantageModel = serviceHelper.getAdvantageModelMapper().selectById(id);
        if(advantageModel != null && !Strings.isNullOrEmpty(advantageModel.getPartNumber()) && !Strings.isNullOrEmpty(advantageModel.getBrand())){
            // 判断当前型号的品牌是否为优势品牌
            QueryWrapper<AdvantageBrand> param = new QueryWrapper<>();
            param.eq(AdvantageModelConstants.BRAND_FIELD, advantageModel.getBrand());
            param.eq(AdvantageModelConstants.ADVANTAGE_STATUS_FIELD, AdvantageStatusEnum.EFFECTIVE.getScStatusCode());
            param.eq(Constants.ENTERPRISE_ID_FIELD, advantageModel.getEnterpriseId());
            List<AdvantageBrand> advantageBrands = serviceHelper.getAdvantageBrandMapper().selectList(param);
            if(advantageBrands != null && advantageBrands.size() > 0){
                // 如果当前优势型号的品牌为优势品牌则判断当前型号是否有库存
                QueryWrapper<Inventory> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq(AdvantageModelConstants.PART_NUMBER_FIELD, advantageModel.getPartNumber());
                queryWrapper.eq(AdvantageModelConstants.BRAND_FIELD, advantageModel.getBrand());
                queryWrapper.eq(Constants.ENTERPRISE_ID_FIELD, enterpriseId);
                List<Inventory> inventories = serviceHelper.getInventoryMapper().selectList(queryWrapper);
                if(inventories != null && inventories.size() > 0){
                    for(Inventory inventory : inventories){
                        if(inventory.getCount() > 0){
                            result = Boolean.TRUE;
                            break;
                        }
                    }
                }
            }
        }

        return result;
    }

    /**
     * 获取可申请优势型号的的库存型号
     * @param inventories 库存信息
     * @param advantageModels 已申请的优势型号信息
     * @return 返回可申请优势型号的的库存型号
     */
    private List<MayApplyInventoryModelPojo> getMayApplyInventoryModelList(List<Inventory> inventories, List<AdvantageModel> advantageModels) {
        List<MayApplyInventoryModelPojo> result = new ArrayList<>();
        if(advantageModels == null || advantageModels.size() == 0){
            for(Inventory inventory : inventories){
                MayApplyInventoryModelPojo mayApplyInventoryModelPojo = new MayApplyInventoryModelPojo();
                BeanUtils.copyProperties(inventory, mayApplyInventoryModelPojo);
                result.add(mayApplyInventoryModelPojo);
            }
        }else{
            for(Inventory inventory : inventories){
                boolean haveInventory = Boolean.FALSE;
                for(AdvantageModel advantageModel : advantageModels){
                    String partNumber = inventory.getPartNumber();
                    String partNumber1 = advantageModel.getPartNumber();
                    String brand = inventory.getBrand();
                    String brand1 = advantageModel.getBrand();
                    if(!Strings.isNullOrEmpty(partNumber) && !Strings.isNullOrEmpty(partNumber1) && !Strings.isNullOrEmpty(brand) && !Strings.isNullOrEmpty(brand1)
                            && partNumber.equals(partNumber1) && brand.equals(brand1)){
                        haveInventory = Boolean.TRUE;
                        break;
                    }
                }

                if(!haveInventory){
                    MayApplyInventoryModelPojo mayApplyInventoryModelPojo = new MayApplyInventoryModelPojo();
                    BeanUtils.copyProperties(inventory, mayApplyInventoryModelPojo);
                    result.add(mayApplyInventoryModelPojo);
                }

            }
        }
        return result;
    }

    /**
     * 恢复优势型号状态时推送mq消息
     * 此方法适用于优势型号原来失效，但由于库存上架修改了优势型号的状态为生效的场景
     * 发送此队列给erp时，不需要审核，优势型号的生效状态即可恢复为正常
     * @param brand 品牌
     * @param partNumber 型号
     * @param enterpriseId 供应商id
     */
    private void restoreAdvantageModelSendMqMsg(String brand, String partNumber, String enterpriseId) throws IOException {
        SpecialsScTopViewEnablePojo specialsScTopViewEnablePojo = new SpecialsScTopViewEnablePojo();
        specialsScTopViewEnablePojo.setBrand(brand);
        specialsScTopViewEnablePojo.setPartNumber(partNumber);
        specialsScTopViewEnablePojo.setEnterpriseID(enterpriseId);
        JSONObject json = (JSONObject) JSONObject.toJSON(specialsScTopViewEnablePojo);

        // 包装发送到rabbitmq的消息内容
        JSONObject result = serviceHelper.packageSendRabbitMqMsgData(json, RabbitMqConstants.SC_ERP_ENABLE_QUEUE);

        log.info("推送给rabbitmq的交换机:[{}],队列:[{}]的消息内容为:[{}]", RabbitMqConstants.SC_ERP_EXCHANGE, RabbitMqConstants.SC_ERP_ENABLE_QUEUE, result.toString());
        serviceHelper.getRabbitMqManager().basicPublish(RabbitMqConstants.SC_ERP_EXCHANGE, RabbitMqConstants.SC_TO_ERP_CRM_QUEUE_NAME, RabbitMqConstants.SC_ERP_ENABLE_QUEUE, null, result.toString().getBytes());

    }

    /**
     * 取消优势型号推送mq消息
     * @param erpId erpId
     */
    private void cancleAdvantageModelSendMqMsg(String erpId) throws IOException {
        JSONObject json = new JSONObject();
        json.put(AdvantageConstants.ID, erpId);

        // 包装发送到rabbitmq的消息内容
        JSONObject result = serviceHelper.packageSendRabbitMqMsgData(json, RabbitMqConstants.SC_ERP_CLOSE_QUEUE);

        log.info("推送给rabbitmq的交换机:[{}],队列:[{}]的消息内容为:[{}]", RabbitMqConstants.SC_ERP_EXCHANGE, RabbitMqConstants.SC_ERP_CLOSE_QUEUE, result.toString());
        serviceHelper.getRabbitMqManager().basicPublish(RabbitMqConstants.SC_ERP_EXCHANGE, RabbitMqConstants.SC_TO_ERP_CRM_QUEUE_NAME, RabbitMqConstants.SC_ERP_CLOSE_QUEUE, null, result.toString().getBytes());

    }

    /**
     * 添加优势型号信息到redis
     * @param advantageModel 优势型号信息
     */
    private void addAdvantangeModelToRedis(AdvantageModel advantageModel){
        String key = RedisKeyPrefixEnum.ADVANTAGE_MODEL_DATA.getCode() + "_" + advantageModel.getPartNumber() + "_" + advantageModel.getBrand() + "_" + advantageModel.getEnterpriseId();
        String apiResultJson = JSONObject.toJSONString(advantageModel, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue);
        serviceHelper.getRedisManager().set(key, apiResultJson);
    }

    /**
     * @desc   从redis中删除优势型号信息
     * @author linuo
     * @time   2023年3月17日14:49:58
     */
    private void deleteAdvantageModelFromRedis(AdvantageModel advantageModel){
        String key = RedisKeyPrefixEnum.ADVANTAGE_MODEL_DATA.getCode() + "_" + advantageModel.getPartNumber() + "_" + advantageModel.getBrand() + "_" + advantageModel.getEnterpriseId();
        serviceHelper.getRedisManager().del(key);
    }
}